package com.ruoyi.system.controller;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import com.ruoyi.common.core.domain.entity.SysDept;
import com.ruoyi.common.utils.security.PermissionUtils;
import com.ruoyi.system.domain.TmdDutyDatePeople;
import com.ruoyi.system.service.ISysDeptService;
import com.ruoyi.system.service.ITmdDutyDatePeopleService;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.*;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.system.domain.TmdDutyApplication;
import com.ruoyi.system.service.ITmdDutyApplicationService;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.common.core.page.TableDataInfo;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

/**
 * 排班申请Controller
 * 
 * @author ruoyi
 * @date 2024-04-20
 */
@Controller
@RequestMapping("/system/application")
public class TmdDutyApplicationController extends BaseController
{
    private String prefix = "system/application";

    @Autowired
    private ITmdDutyApplicationService tmdDutyApplicationService;
    @Autowired
    private ITmdDutyDatePeopleService tmdDutyDatePeopleService;

    @Autowired
    private ISysDeptService iSysDeptService;

    @RequiresPermissions("system:application:view")
    @GetMapping()
    public String application(Model model)
    {
        List<SysDept> deptList = iSysDeptService.selectAllDeptList();
        model.addAttribute("deptList",deptList);
        return prefix + "/application";
    }

    @GetMapping("/getAllApp")
    @ResponseBody
    public List<TmdDutyApplication> getAllApp()
    {
        List<TmdDutyApplication> list = tmdDutyApplicationService.getAllApp();
        return list;
    }

    /**
     * 查询排班申请列表
     */
    @RequiresPermissions("system:application:list")
    @PostMapping("/list")
    @ResponseBody
    public TableDataInfo list(TmdDutyApplication tmdDutyApplication)
    {
        startPage();
        List<TmdDutyApplication> list = tmdDutyApplicationService.selectTmdDutyApplicationList(tmdDutyApplication);
        return getDataTable(list);
    }

    /**
     * 导出排班申请列表
     */
    @RequiresPermissions("system:application:export")
    @Log(title = "排班申请", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    @ResponseBody
    public AjaxResult export(TmdDutyApplication tmdDutyApplication)
    {
        List<TmdDutyApplication> list = tmdDutyApplicationService.selectTmdDutyApplicationList(tmdDutyApplication);
        ExcelUtil<TmdDutyApplication> util = new ExcelUtil<TmdDutyApplication>(TmdDutyApplication.class);
        return util.exportExcel(list, "排班申请数据");
    }

    /**
     * 新增排班申请
     */
    @GetMapping("/add")
    public String add(Model model)
    {
        List<SysDept> deptList = iSysDeptService.selectAllDeptList();
        model.addAttribute("deptList",deptList);
        return prefix + "/add";
    }

    /**
     * 新增保存排班申请
     */
    @RequiresPermissions("system:application:add")
    @Log(title = "排班申请", businessType = BusinessType.INSERT)
    @PostMapping("/add")
    @ResponseBody
    public AjaxResult addSave(TmdDutyApplication tmdDutyApplication,String[] dutyPersonId,String dutyDate_1)
    {
        // 将前端传递的值班人、值班日期存入到列表中
        Date date=new Date();
        SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd");
        List<TmdDutyDatePeople> dutyDatePeopleList=new ArrayList<>();
        TmdDutyDatePeople tmdDutyDatePeople=new TmdDutyDatePeople();
        long time=date.getTime();
        for (String eve:dutyPersonId) {
            try {
                date=sdf.parse(dutyDate_1);
            } catch (ParseException e) {
                e.printStackTrace();
            }
            tmdDutyDatePeople=new TmdDutyDatePeople();
            tmdDutyDatePeople.setDutyDate(date);
            tmdDutyDatePeople.setDutyPersonId(Long.parseLong(eve));
            dutyDatePeopleList.add(tmdDutyDatePeople);
            time+=24*60*60*1000;
            date.setTime(time);
            dutyDate_1= sdf.format(date);
        }
        System.out.println(dutyDatePeopleList);
//      设置当前登录人
        tmdDutyApplication.setCreatePerson((String) PermissionUtils.getPrincipalProperty("userName"));
//      添加日期和值班人
//        tmdDutyDatePeopleService.insertTmdDutyDatePeopleList(dutyDatePeopleList);
        return toAjax(tmdDutyApplicationService.insertTmdDutyApplication(tmdDutyApplication,dutyDatePeopleList));
    }

    /**
     * 修改排班申请
     */
    @RequiresPermissions("system:application:edit")
    @GetMapping("/edit/{id}")
    public String edit(@PathVariable("id") Long id, ModelMap mmap,Model model)
    {
        TmdDutyApplication tmdDutyApplication = tmdDutyApplicationService.selectTmdDutyApplicationById(id);
//        mmap.put("tmdDutyApplication", tmdDutyApplication);
        model.addAttribute("tmdDutyApplication", tmdDutyApplication);
        List<TmdDutyDatePeople> dutyDatePeopleList = tmdDutyDatePeopleService.selectTmdDutyDatePeopleByAppId(id);
        model.addAttribute("tmdDutyDatePeopleList", dutyDatePeopleList);
        return prefix + "/edit";
    }

    /**
     * 修改保存排班申请
     */
    @RequiresPermissions("system:application:edit")
    @Log(title = "排班申请", businessType = BusinessType.UPDATE)
    @PostMapping("/edit")
    @ResponseBody
    public AjaxResult editSave(TmdDutyApplication tmdDutyApplication,Date[] dutyDate,String[] dutyPersonId)
    {
        // 判断是不是连续的七天
        long[] times=new long[dutyDate.length];
        long day=24*60*60*1000;
        int index=0;
        for (Date eve: dutyDate) {
            times[index++]=eve.getTime();
        }
        for (int i = 0; i < times.length-1; i++) {
            index = i;
            for (int j = i+1; j < times.length; j++) {
                if(times[j]<times[i]){
                    index=j;
                }
            }
            long temp=times[i];
            times[i]=times[index];
            times[index]=temp;
        }
        for (int i = 0; i < times.length-1; i++) {
            if (times[i]+day!=times[i+1]){
                return error("不是连续的七天");
            }
        }

        // 先把从前端取到的数据放入list，用于修改
        List<TmdDutyDatePeople> dutyDatePeopleList=new ArrayList<>();
        TmdDutyDatePeople tmdDutyDatePeople=new TmdDutyDatePeople();

        for (int i =0; i<dutyPersonId.length; i++){
            tmdDutyDatePeople=new TmdDutyDatePeople();
            tmdDutyDatePeople.setDutyDate(dutyDate[i]);
            if (dutyPersonId[i]==null || dutyPersonId[i]==""){
                return error("请选择值班人");
            }
            tmdDutyDatePeople.setDutyPersonId(Long.parseLong(dutyPersonId[i]));
            tmdDutyDatePeople.setDutyApplicationId(tmdDutyApplication.getId());
            dutyDatePeopleList.add(tmdDutyDatePeople);
        }
        // 先删后插达到批量修改的效果
        tmdDutyDatePeopleService.deleteTmdDutyDatePeopleByAppIds(String.valueOf(tmdDutyApplication.getId()));
        tmdDutyDatePeopleService.insertTmdDutyDatePeopleList(dutyDatePeopleList);
        return toAjax(tmdDutyApplicationService.updateTmdDutyApplication(tmdDutyApplication));
    }

    /**
     * 查看排班申请
     */
    @RequiresPermissions("system:application:detail")
    @GetMapping("/detail/{id}")
    public String detail(@PathVariable("id") Long id, ModelMap mmap,Model model)
    {
        TmdDutyApplication tmdDutyApplication = tmdDutyApplicationService.selectTmdDutyApplicationById(id);
        model.addAttribute("tmdDutyApplication", tmdDutyApplication);
        List<TmdDutyDatePeople> dutyDatePeopleList = tmdDutyDatePeopleService.selectTmdDutyDatePeopleByAppId(id);
        model.addAttribute("tmdDutyDatePeopleList", dutyDatePeopleList);
        return prefix + "/detail";
    }

    /**
     * 删除排班申请
     */
    @RequiresPermissions("system:application:remove")
    @Log(title = "排班申请", businessType = BusinessType.DELETE)
    @PostMapping( "/remove")
    @ResponseBody
    public AjaxResult remove(String ids)
    {
        tmdDutyDatePeopleService.deleteTmdDutyDatePeopleByAppIds(ids);
        return toAjax(tmdDutyApplicationService.deleteTmdDutyApplicationByIds(ids));
    }


}
